import DWC_DCEmoticonItem from "./DWC_DCEmoticonItem/DWC_DCEmoticonItem";

const { ccclass, property } = cc._decorator;
/** 复杂聊天表情包 create by tm */
@ccclass
export default class DWC_DCEmoticon extends cc.Component {
    //-----------组件区----------
    @property(cc.ScrollView)
    scroll_emoticon: cc.ScrollView = null;
    @property(cc.Prefab)
    dcEmoticonItem_pfb: cc.Prefab = null;
    /** 表情资源 */
    @property(cc.SpriteAtlas)
    atlas_emoticon: cc.SpriteAtlas = null;
    //-----------变量区----------
    emoticonParent: cc.Node = null;
    /** 定时计时器 */
    timingTimer: number = null;
    onLoad() {
        this.addEvent();
    }
    /** 添加事件 */
    addEvent(): void {
        this.node.on(`dwc_detailChat_touchEmoticonItem`, this.touchChooseEmoticon, this);//点击选择表情
    }
    /** 移除事件 */
    removeEvent(): void {
        this.node.off(`dwc_detailChat_touchEmoticonItem`, this.touchChooseEmoticon, this);
    }
    /** 初始化(外界调用) */
    init(_args): void {
        this.emoticonParent = _args.emoticonParent;
        this.setAllEmoticon();
    }
    /** 设置所有表情 */
    setAllEmoticon(): void {
        let _h: number = 0;
        this.atlas_emoticon.getSpriteFrames().forEach((_v, _idx) => {
            let _node = cc.instantiate(this.dcEmoticonItem_pfb);
            let _item: DWC_DCEmoticonItem = _node.getComponent(_node.name);
            _node.parent = this.scroll_emoticon.content;
            if (_idx % 5 == 0) {
                _h += _node.height + this.scroll_emoticon.content.getComponent(cc.Layout).spacingY;
            }
            _item.init({
                sf: _v,
                idx: _idx,
                emoticonNode: this.node
            });
        });
        this.scroll_emoticon.content.height = Math.ceil(_h);
    }
    /** 点击选择表情 */
    touchChooseEmoticon(_evt): void {
        if (!_evt && this.emoticonParent) return;
        this.emoticonParent.emit(`dwc_detailChat_touchEmoticon`, _evt);
        this.node.destroy();
    }
    /** 定时关闭 
     * @param _time 时间 单位秒
    */
    timingClose(_time: number = 1): void {
        this.timingTimer && clearTimeout(this.timingTimer);
        this.timingTimer = setTimeout(() => {
            this.node.destroy();
        }, _time * 1000);
    }
    onDestroy() {
        this.timingTimer && clearTimeout(this.timingTimer);
        this.removeEvent();
    }
}
